package com.by.toolkitspring.support;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class EncryptSupport {

    @Value("${encrypt.salt}")
    private String encryptKey;

    private static final String XOR_TABLE = "YJUC*8L*6ega8RqxQ73W!C&GCyZhiwhz"; // 32位随机字符串用于异或

    private AES aes;

    @EventListener(ApplicationStartedEvent.class)
    public void initEncrypt(ApplicationStartedEvent event) {
        aes = SecureUtil.aes(encryptKey.getBytes(StandardCharsets.UTF_8));
    }

    public String encrypt(String phone) {
        return aes.encryptHex(xor(phone), StandardCharsets.UTF_8);
    }

    public String decrypt(String phone) {
        return xor(aes.decryptStr(phone, StandardCharsets.UTF_8));
    }

    private String xor(String encryptContent) {
        StringBuilder stringBuilder = new StringBuilder("");
        for (int i = 0; i < encryptContent.length(); i++) {
            stringBuilder.append((char) (encryptContent.charAt(i) ^ XOR_TABLE.charAt(i % XOR_TABLE.length())));
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        EncryptSupport encryptSupport = new EncryptSupport();
        encryptSupport.encryptKey = "e1674gdeggdvvuy!!784974%$@*($BD*";
        encryptSupport.initEncrypt(null);
        String encryptPhone = encryptSupport.encrypt("{dsjakldjsakldjsalkdsajlkdsajdklsjsaldjsalkdjlkasjdnkowencjierbcvhrueybveurybuyewb32y847218974983279847398}");
        System.out.println(encryptPhone);
        System.out.println(encryptSupport.decrypt(encryptPhone));
    }

}
